const Mock = require("mockjs");
const fs = require("fs")
const bodyParser = require('body-parser');
const users = require("../dongtluyou/src/mock/user.json")
const data = Mock.mock({
    "list|10":[
        {
            "title":"@cword(10,20)",
            "id":"@id",
             "children|5":[
                 {
                    "title":"@cword(10,20)",
                     "img":"@Image(100x100,@color)"
                 }
             ]
        }
    ]
})
module.exports = {
    devServer:{
        before(app){
            app.get("/list",(req,res)=>{
                res.send(data.list)
            })
            // z这个包是用来解析post请求的
            app.use(bodyParser.json())
            // 登陆接口
            app.post("/login",(req,res)=>{
                let {username,password} = req.body
                if (username == "zhaozhihao" && password =="123") {
                    res.send({
                        code:1,
                        msg:"登陆成功"
                    })
                } else {
                    res.send({
                        code:0,
                        msg:"登陆失败"
                    })
                }
              
            })
            // 注册接口
            app.post("/zhuce",(req,res)=>{
                console.log(req.body)
                let {username,password} = req.body
                //1.先看json里有没有
                let newArr = users.filter((item,index)=>{
                    return item.username == username
                })
                if (newArr.length) {
                    res.send(
                        {
                            code:402,
                            msg:"您已注册，直接登陆"
                        }
                    )
                } else {
                    users.push({
                        username,
                        password
                    })
                    fs.writeFileSync("./src/mock/user.json",JSON.stringify(users))
                    res.send({
                        code:200,
                        msg:"登陆成功"
                    })
                }

            })
        }
    }
}
 